<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/18
 * Time: 23:42
 */

namespace app\api\controller\v1;


use app\api\controller\Common;
use app\common\lib\exception\ApiException;

class News extends Common
{

    /**
     * 文章列表接口
     * @return array
     */
    public function index(){
        // validate 验证机制，做相关校验

        $data = input('get.');

        $whereData['status'] = config('code.status_normal');
        if (!empty($data['catid'])){
            $whereData['catid'] = input('get.catid', 0 , 'intval');
        }
        if (!empty($data['title'])){
            $whereData['title'] = ['like', '%'.$data['title'].'%'];
        }

        $this->getPageAndSize($data);
        $total = model('News')->getNewsCountByCondition($whereData);
        $news = model('News')->getNewsByCondition($whereData, $this->from, $this->size);

        $result = [
            'total' => $total,
            'page_nium' => ceil($total/$this->size),
            'list' => $this->getDealNews($news)
        ];

        return show(config('code.success'), 'OK', $result, 200);
    }

    /**
     * 获取详情接口
     */
    public function read(){
        $id = input('param.id', 0, 'intval');
        if (empty($id)){
            return  new ApiException('id is not', 404);
        }
        try {
            $news = model('News')->get($id);
        }catch (\Exception $e){
            return new ApiException($e->getMessage(), 400);
        }
        if (empty($news) || $news->status != config('code.status_normal')){
           return new ApiException('不存在该新闻', 404);
        }
    
        //阅读数自增
        try {
            model('News')->where(['id' => $id])->setInc('read_count');
        }catch (\Exception $e){
            return new ApiException('setInc error', 404);
        }

        $cats = config('cat.lists');
        $news->catnmame = $cats[$news->catid];
        return show(config('code.success'), 'OK', $news, 200);
    }



}